package com.cgb2110.serve.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgb2110.serve.mapper.MenuRoleMapper;
import com.cgb2110.serve.pojo.MenuRole;
import com.cgb2110.serve.pojo.RespBean;
import com.cgb2110.serve.pojo.Role;
import com.cgb2110.serve.service.IMenuRoleService;
import com.cgb2110.serve.service.IRoleService;
import com.cgb2110.serve.service.impl.MenuRoleServiceImpl;
import com.cgb2110.serve.service.impl.RoleServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/system/basic/permiss")
public class PermisingController {
    @Autowired
    private RoleServiceImpl roleService;

    @Autowired
    private MenuRoleServiceImpl menuRoleService;

    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }

    @ApiOperation(value = "添加所有角色")
    @PostMapping("/role")
    public RespBean addRoles(@RequestBody Role role){
        if (role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if(roleService.save(role)){
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/{id}")
    public RespBean deleteRolesById(@PathVariable Integer rid){
        if(roleService.removeById(rid)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "根据用户id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRId(@PathVariable Integer rid){
        QueryWrapper<MenuRole> queryWrapper = new QueryWrapper();
        return  menuRoleService.list(queryWrapper.eq("rid", rid)).stream().
                map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(Integer rid,Integer[] mids){
        return menuRoleService.updateMenuRole(rid,mids);
    }
}
